package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.QuestionMapper;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.*;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.UserLocationVo;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/8 20:48
 */

@Service
public class TanHuaService {

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private QuestionMapper questionMapper;

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    @Value("tanhua.default.recommend.users")
    private String defaultRecommendUsers;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    /**
     * 根据半径范围位置，查询附近的人：
     *
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> searchNearUsers(String gender, Double distance) {

        //查询当前用户：
        User user = UserThreadLocal.get();

        //查询当前用户的经纬度：
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        if (ObjectUtil.isEmpty(userLocationVo)) {
            //如果没有，则返回空集合：
            return ListUtil.empty();
        }

        //不为空：根据经纬度查询：
        PageInfo<UserLocationVo> pageInfo = userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                distance, 1, 50);

        List<UserLocationVo> records = pageInfo.getRecords();
        if (records.size() == 0) {
            //没有指定范围内的用户
            return ListUtil.empty();
        }
        //获取所有的查询的usr 的id:
        List<Object> ids = new ArrayList<>();
        for (UserLocationVo record : records) {
            ids.add(record.getUserId());
        }

        //构造筛选条件:
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", ids);
        if (StrUtil.equals(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        }
        if (StrUtil.equals(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = userInfoService.queryRecommendationUserInfo(queryWrapper);
        //构造userId 与 userInfo的map对应：
//        Map<Long, UserInfo> map = userInfoList.stream().collect(Collectors.toMap(u -> u.getUserId(), Function.identity()));

        //封装信息：
        List<NearUserVo> result = new ArrayList<>();
        NearUserVo nearUserVo;
        for (UserLocationVo record : records) {
            if (record.getUserId().equals(user.getId())) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(record.getUserId(), userInfo.getUserId())) {

                    nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    result.add(nearUserVo);
                    break;
                }
            }
//            nearUserVo = new NearUserVo();
//            nearUserVo.setUserId(record.getUserId());
//            nearUserVo.setAvatar(map.get(record.getUserId()).getLogo());
//            nearUserVo.setNickname(map.get(record.getUserId()).getNickName());
//            result.add(nearUserVo);
        }

        return result;
    }

    /**
     * 查询主页个人信息
     *
     * @param userId
     * @return
     */
    public TodayBest queryPersonInfo(Long userId) {

        User user = UserThreadLocal.get();

        //查询的推荐表的记录，用于获取得分：
        RecommendUser recommendUser = recommendUserApi.queryPersonInfo(userId, user.getId());
        Double score = null;
        if (!ObjectUtil.isEmpty(recommendUser)) {
            score = recommendUser.getScore();
        }
        if (ObjectUtil.isEmpty(score)) {
            //如果没有缘分值，设置默认98
            score = 98d;
        }

        //不记录自己的访客记录：
        if (!user.getId().equals(userId)) {
            //记录来访记录：
            visitorsApi.saveVisitors(userId, user.getId(), "个人主页");
        }

        UserInfo userInfo = userInfoService.queryTodayBestInfo(userId);
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);
        todayBest.setFateValue(score.longValue());
        todayBest.setAge(userInfo.getAge());
        todayBest.setGender(userInfo.getSex().name());
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setAvatar(userInfo.getLogo());

        return todayBest;
    }


    /**
     * 查询陌生人的问题：
     *
     * @param userId
     * @return
     */
    public String findQuestion(Long userId) {

        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Question question = questionMapper.selectOne(queryWrapper);

        if (ObjectUtil.isEmpty(question)) {
            //如果没有设置问题，则给他来一个默认问题：
            return "留下你的微信number~~~";
        }
        return question.getTxt();
    }


    /**
     * 回复陌生人问题：
     *
     * @param userId
     * @param replyQuestionTxt
     * @return
     */
    public Boolean replyQuestion(Long userId, String replyQuestionTxt) {

        //获取用户信息：
        User user = UserThreadLocal.get();

        UserInfo userInfo = userInfoService.queryTodayBestInfo(user.getId());

        //构建消息体：
        Map<String, Object> mapMsg = new HashMap<>();
        mapMsg.put("userId", user.getId());
        mapMsg.put("huanXinId", "HX_" + user.getId());
        mapMsg.put("nickname", userInfo.getNickName());
        mapMsg.put("strangerQuestion", this.findQuestion(userId));
        mapMsg.put("reply", replyQuestionTxt);

        //陌生人非好友，得用管理员身份发送消息：
        return huanXinApi.sendMessageByAdmin("HX_" + userId, HuanXinMessageType.TXT, JSONUtil.toJsonStr(mapMsg));
    }

    /**
     * 查询推荐好友列表：
     *
     * @return
     */
    public List<TodayBest> queryCardList() {

        User user = UserThreadLocal.get();
        int count = 50;
        List<RecommendUser> recommendUserList = recommendUserService.queryCardList(user.getId(), count);

        if (CollUtil.isEmpty(recommendUserList)) {
            recommendUserList = new ArrayList<>();
            //默认推荐列表
            List<String> list = StrUtil.split(defaultRecommendUsers, ',');
            for (String userId : list) {
                RecommendUser recommendUser = new RecommendUser();

                recommendUser.setToUserId(user.getId());
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUserList.add(recommendUser);
            }
        }

        //随机赛选10个返回：
        int size = Math.min(10, recommendUserList.size());

        //构造默认十个不重复的返回：
        Set<RecommendUser> result = new HashSet<>();

        do {
            int index = RandomUtil.randomInt(0, recommendUserList.size());
            result.add(recommendUserList.get(index));
        } while (result.size() < size);


        //获取recommendUser的ids,去查询userInfo填充TodayBest:
        List<Object> ids = CollUtil.getFieldValues(result, "userId");

        List<UserInfo> userInfos = userInfoService.queryUserInfoByUserIdList(ids);

        //构造返回的todayBest的集合：
        List<TodayBest> todayBests = new ArrayList<>();
        TodayBest todayBest = null;
        for (UserInfo userInfo : userInfos) {
            todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;
    }


    /**
     * 喜欢这个用户：
     *
     * @param loveUserId
     * @return
     */
    public Boolean loveUser(Long loveUserId) {

        User user = UserThreadLocal.get();

        Boolean result = userLikeApi.likeUser(user.getId(), loveUserId);

        if (result) {
            //如果喜欢成功，看是否他们互相喜欢：如果互相喜欢，注册好友：
            Boolean mutualLike = userLikeApi.isMutualLike(user.getId(), loveUserId);
            if (mutualLike) {
                //互相喜欢了：注册好友关系：
                imService.contactsFriends(loveUserId.intValue());
            }
        }

        return result;
    }


    /**
     * 不喜欢这个用户：
     *
     * @param disLoveUserId
     * @return
     */
    public Boolean disLoveUser(Long disLoveUserId) {

        User user = UserThreadLocal.get();

        return userLikeApi.notLikeUser(user.getId(), disLoveUserId);
    }
}






























